<template>
	<view class="page-login">
		<view class="container-logo">
			<box-logo></box-logo>
		</view>
		<image class="img-title-login" src="/static/login_title@3x.png"></image>
		<view class="box-login">
			<view class="box-login-item">
				<input class="txt-input" maxlength="11" type="tel" v-model="mobile" placeholder="请输入手机号"
					placeholder-style="color:rgba(255,255,255,0.3);" @input="onInputMobile" />
				<image v-if="mobile.length" class="icon-login-delete" src="/static/login_delete@3x.png"
					@tap="onClearMobile"></image>
			</view>
			<view class="box-login-item">
				<input class="txt-input" v-model="code" placeholder="请输入验证码" type="digit"
					placeholder-style="color:rgba(255,255,255,0.3);" @input="onInputCode" maxlength="4" />
				<SendSmsButton :mobile="mobile" @setCacheCode="setCacheCode"></SendSmsButton>
			</view>
		</view>
		<view :class="['btn-login',!mobile||!code? 'disabled':'']" @tap="handleLogin">登录/注册</view>
		<view class="wrap-bottom">
			<view class="box-login-type-choose">
				<template v-if="weixinSupport||appleSupport">
					<view class="box-login-type-title">
						<view class="line"></view>
						<view class="cont-title">其他登录方式</view>
						<view class="line"></view>
					</view>
					<view class="box-login-type-items">
						<image v-if="univerifySupport" class="img-login-type" src="/static/univerify@3x.png"
							@tap="onUniverifyLogin"></image>
						<image v-if="appleSupport" class="img-login-type" src="/static/apple@3x.png"
							@tap="onLogin('apple')">
						</image>
						<image v-if="weixinSupport" class="img-login-type" src="/static/wechat@3x.png"
							@tap="onLogin('weixin')">
						</image>
					</view>
				</template>


			</view>

			<view class="box-privacy" :style="safePaddingBottom" @tap="onAgree">
				<view class="box-agree">
					<image v-if="!agreePrivacy" class="icon-agree" src="@/static/icon_unagree.png"></image>
					<image v-if="agreePrivacy" class="icon-agree" src="@/static/icon_agree.png"></image>
				</view>
				<view>已阅读并同意<text class="cont-privacy" @tap.stop="toPrivacy">《服务条款》</text>和<text
						class="cont-privacy" @tap.stop="toPrivacy">《用户协议》</text></view>
			</view>
		</view>

	</view>
</template>
<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from "@dcloudio/uni-app"
	import {
		computed,
		nextTick,
		ref
	} from "vue"
	import {
		LOGIN_TYPE,
		RegMobile
	} from "@/utils/constant.js"
	import {
		showToast
	} from "@/utils/frameApi.js"
	import {
		getOauthProvider,
		thirdLogin
	} from "@/utils/index.js"
	import BoxLogo from "/components/box-logo/index.vue"
	import SendSmsButton from "/components/send-sms-button/index.vue"
	import {
		useUser
	} from "@/hooks/useUser.js"
	import {
		mobileLogin,
		weixinLogin,
		mpWeixinLogin,
		appleLogin
	} from "@/http/apis/loginAPI.js"
	import {
		userInfoAPI
	} from "@/http/apis/customerBaseAPI.js"
	const userStore = useUser()
	let univerifySupport = ref(false)
	let weixinSupport = ref(false);
	let appleSupport = ref(false);
	getOauthProvider().then(res => {
		univerifySupport.value = res.univerifySupport;
		weixinSupport.value = res.weixinSupport;
		appleSupport.value = res.appleSupport;
	})
	// 登录
	let logining = false;
	let redirectUrl = ref("");
	let agreePrivacy = ref(false)
	onLoad((options) => {
		let redirect = options && options.redirect ? decodeURIComponent(options.redirect) : '';
		redirectUrl.value = redirect
	})
	//设置页面全屏
	onShow(() => {
		logining = false;
		// #ifdef APP-PLUS
		// plus.navigator.setFullscreen(true); //隐藏手机顶部状态栏
		plus.navigator.hideSystemNavigation(); //隐藏手机底部导航按键
		// #endif
	})
	//监听页面卸载事件 如果不加这句，会导致跳转到别的页面后也是全屏
	onUnload(() => {
		// #ifdef APP-PLUS
		// plus.navigator.setFullscreen(false); //显示手机顶部状态栏
		plus.navigator.showSystemNavigation(); //显示手机底部导航按键
		// #endif
	})
	let mobile = ref("");
	const onInputMobile = () => {
		let val = mobile.value.replace(/\D/g, '');
		nextTick(() => {
			mobile.value = val;
		})
	}
	const onClearMobile = () => {
		mobile.value = "";
	}
	let code = ref("");
	let cacheCode = ref("")
	const onInputCode = () => {
		let val = code.value.replace(/\D/g, '');
		nextTick(() => {
			code.value = val;
		})
	}
	const setCacheCode = (val) => {
		console.log(val, ">>>>>>>>>>>>>>>>j")
		cacheCode.value = val
	}
	// 登录

	const toIndexPage = async () => {
		// if (redirectUrl.value) {
		// 	uni.navigateBack();
		// 	return;
		// }
		uni.switchTab({
			url: '/pages/index/index',
			success: () => {},
			fail: (e) => {
				console.log(e)
			}
		})
	}

	const handleLogin = async () => {
		if (!agreePrivacy.value) {
			showToast({
				title: "请先阅读并同意服务条款和用户协议"
			})
			return
		}
		if (!RegMobile.test(mobile.value)) {
			showToast({
				title: '请输入正确的手机号'
			})
			return
		}
		if (!code.value) {
			showToast({
				title: '请输入验证码'
			})
			return;
		}
		// console.log(code.value, cacheCode.value, ">>>>>>>>>>>>>>>>>")
		// if (code.value != cacheCode.value) {
		// 	showToast({
		// 		title: '验证码不正确'
		// 	})
		// 	return;
		// }
		if (logining) {
			return;
		}
		logining = true;
		let loginResult = await mobileLogin({
			user_phone: mobile.value,
			pre_cmd_para_msg_content: code.value
		}).catch((err) => {
			console.log(loginResult, ">>>>>>>>>>login...fail")
			logining = false;
		})

		if (!loginResult) {
			logining = false;
			console.log(111)
		}
		console.log(loginResult, '>>>>>>>>>>>>>loginResult')
		userStore.setUserInfo(loginResult || {})
		if (loginResult) {
			toIndexPage()
		}

	}
	// 登录
	const onLogin = async (server) => {
		try {
			if (!agreePrivacy.value) {
				showToast({
					title: "请先阅读并同意服务条款和用户协议"
				})
				return
			}
			if (!server) {
				uni.showToast({
					icon: 'none',
					title: '目前暂不支持该方式登录'
				})
				return;
			}
			let thirdLoginParams = {
				provider: server
			}
			if (server == 'weixin') {
				thirdLoginParams.onlyAuthorize = true
			}
			if (logining) {
				return;
			}
			logining = true;
			let resultThirdLogin = await thirdLogin(thirdLoginParams).catch(err => {
				logining = false;
				console.log(err)
			});
			if (!resultThirdLogin) {
				logining = false;
				showToast({
					title: "登录失败"
				})
				// uni.showToast({
				// 	icon: 'none',
				// 	title: `${LOGIN_TYPE[server]}登录失败`
				// })
				return;
			}
			let postData = null;
			let loginResult = null;
			if (server == 'weixin') {
				postData = {
					code: resultThirdLogin.code
				}
				// #ifdef APP-PLUS
				loginResult = await weixinLogin(postData).catch(err => {
					logining = false
					console.log(err, ">>>weixinLogin...fail")
				});
				
				if (!loginResult) {
					let tmpUserInfo = loginResult?.public_user_info || {};
					if (tmpUserInfo.id_public_user_info) {
						let updateNickData = {
							invoke_method: "change_user_info",
							nick_name: tmpUserInfo.weichat_name||"",
							pre_db_para_id_public_user_info: tmpUserInfo.id_public_user_info
						};
						let tmpUpdateNickName=await userInfoAPI(updateNickData).catch((err)=>{
							console.log(err,">>>err...UpdateNickName")
						})
						if(tmpUpdateNickName&&tmpUserInfo.weichat_name){
							tmpUserInfo.nick_name=tmpUserInfo.weichat_name;
						}
					}

				}

				// #endif
				// #ifdef MP-WEIXIN
				loginResult = await mpWeixinLogin(postData).catch(err => {
					logining = false;
					console.log(err, ">>>weixin-mp-login...fail")
				})
				// #endif

			}
			if (server == 'apple') {
				postData = {
					pre_cmd_para_open_id: resultThirdLogin?.appleInfo?.user || '',
					pre_cmd_para_user_email: resultThirdLogin?.appleInfo.email || '',
				}
				loginResult = await appleLogin(postData).catch(err => {
					console.log(err, ">>>appLogin...fail")
				});
			}
			if (loginResult) {
				logining = false;
				showToast({
					title: "登录成功"
				})
				// uni.showToast({
				// 	icon: 'none',
				// 	// title: `${LOGIN_TYPE[server]}登录成功`
				// 	title:'登录成功'
				// })
				userStore.setUserInfo(loginResult || {})
				toIndexPage()
			} else {
				showToast({title:"登录失败"})
				logining = false;
			}
		} catch (e) {
			console.log(e, 111)
			//TODO handle the exception
			logining = false;
		}


	}
	// 一键登录
	const onUniverifyLogin = async () => {
		uni.preLogin({
			provider: 'univerify',
			success(resPreLogin) { //预登录成功
				// 显示一键登录选项
				console.log("success>>>", resPreLogin)
				uni.login({
					provider: 'univerify',
					univerifyStyle: { // 自定义登录框样式
						//参考`univerifyStyle 数据结构`
						"fullScreen": true, // 是否全屏显示，默认值： false
						"backgroundColor": "#213343", // 授权页面背景颜色，默认值：#ffffff
						"icon": {
							"path": "/static/logo_border.png", // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
							"width": "60px", //图标宽度 默认值：60px
							"height": "60px" //图标高度 默认值：60px
						},
						"closeIcon": {
							"path": "/static/deleted@3x.png" // 自定义关闭按钮，仅支持本地图片。 HBuilderX3.3.7+版本支持
						},
						"phoneNum": {
							"color": "#ffffff" // 手机号文字颜色 默认值：#202020  
						},
						"slogan": {
							"color": "#ffffff" //  slogan 字体颜色 默认值：#BBBBBB  
						},
						"authButton": {
							"normalColor": "#48C282", // 授权按钮正常状态背景颜色 默认值：#3479f5  
							"highlightColor": "#48C282", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）  
							"disabledColor": "#48C282", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）  
							"textColor": "#ffffff", // 授权按钮文字颜色 默认值：#ffffff  
							"title": "本机号码一键登录", // 授权按钮文案 默认值：“本机号码一键登录”  
							"borderRadius": "24px" // 授权按钮圆角 默认值："24px" （按钮高度的一半）
						},
						"otherLoginButton": {
							"visible": true, // 是否显示其他登录按钮，默认值：true  
							"normalColor": "", // 其他登录按钮正常状态背景颜色 默认值：透明 
							"highlightColor": "", // 其他登录按钮按下状态背景颜色 默认值：透明 
							"textColor": "#FFFFFF", // 其他登录按钮文字颜色 默认值：#656565  
							"title": "其他登录方式", // 其他登录方式按钮文字 默认值：“其他登录方式”  
							"borderColor": "#FFFFFF", //边框颜色 默认值：透明（仅iOS支持）  
							"borderRadius": "24px" // 其他登录按钮圆角 默认值："24px" （按钮高度的一半）
						},
						"privacyTerms": {
							"defaultCheckBoxState": true, // 条款勾选框初始状态 默认值： true
							"isCenterHint": true, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
							"uncheckedImage": "/static/icon_unagree.png", // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)   
							"checkedImage": "/static/icon_agree.png", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)   
							"checkBoxSize": 12, // 可选 条款勾选框大小，仅android支持
							"textColor": "#FFFFFF", // 文字颜色 默认值：#BBBBBB  
							"termsColor": "#00FFF6", //  协议文字颜色 默认值： #5496E3  
							"prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”  
							"suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”  
							"privacyItems": [ // 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效  
								{
									"url": "https://duzikai4aigcugc5001.downline.cn/004_mobile_web_site_lite_mod__aigc_ugc/dist/index.html#/service", // 点击跳转的协议详情页面  
									"title": "服务条款" // 协议名称  
								},
								{
									"url": "https://duzikai4aigcugc5001.downline.cn/004_mobile_web_site_lite_mod__aigc_ugc/dist/index.html#/privacy", // 点击跳转的协议详情页面  
									"title": "用户协议" // 协议名称  
								}
							]
						},
					},
					success(res) { // 登录成功
						console.log(res, ">>res")
						// console.log(res,res.authResult,">>>success"); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
						let user_openid = "";
						let user_access_token = "";
						if (res.authResult && res.authResult.openid && res.authResult
							.access_token) {
							console.log("step1111")
							user_openid = res.authResult.openid;
							user_access_token = res.authResult.access_token;
							uniCloud.callFunction({
								name: "community",
								data: {
									...res.authResult
								}
							}).then(async (resCommunity) => {
								console.log(resCommunity, ">>>>resCommunity")
								if (resCommunity.result.code === 0) {
									let loginParams = {
										pre_cmd_para_open_id: user_openid || '',
										pre_cmd_para_phone_user: resCommunity
											.result.phoneNumber || '',
									}
									console.log(loginParams, ">>>loginParams")
									let loginResult = await appleLogin(loginParams)
										.catch(err => {
											console.log(err, ">>>appLogin...fail")
											showToast({
												title: "登录失败,请重试"
											})
										});
									console.log(loginResult, ">>>>loginResult")
									if (loginResult) {
										uni.closeAuthView()
										showToast({
											title: "登录成功"
										})
										userStore.setUserInfo(loginResult || {})
										toIndexPage()
									} else {
										showToast("登录失败，请重试")
										uni.closeAuthView()
									}
								} else {
									showToast("登录失败，请重试")
									uni.closeAuthView()
								}
							}).catch((err) => {
								showToast({
									title: "登录失败，请重试"
								})
								uni.closeAuthView()
							})
						} else {
							showToast({
								title: "登录失败，请重试"
							})
							uni.closeAuthView()
						}

					},
					fail(res) { // 登录失败
						// showToast({
						// 	title: "登录失败，请重试"
						// })
						console.log(res, ">>>")
						console.log(res.errCode)
						console.log(res.errMsg)
						if (res.code == 30002) {
							uni.closeAuthView()
						}

					}
				})
			},
			fail(err) { // 预登录失败
				// 不显示一键登录选项（或置灰）
				// 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
				if(err.code==30005){
					showToast({title:"请先开启数据网络或蜂窝数据"})
				}
				console.log(err, ">>>")
				
				console.log(err.errCode)
				console.log(err.errMsg)
			}
		})
	}

	// 获取底部安全距离
	const safePaddingBottom = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		// console.log(systemInfo,">>>>>>>>>>")
		let bottom = uni.upx2px(25)

		if (systemInfo.platform.toLowerCase() == 'ios') {

			// #ifdef APP-PLUS
			bottom = 0
			// #endif

		}
		return {
			"paddingBottom": `${systemInfo?.safeAreaInsets?.bottom||bottom}px`
		}
	})
	// 点击阅读同意
	const onAgree = () => {
		agreePrivacy.value = !agreePrivacy.value
	}
	// 隐私协议政策
	const toPrivacy = () => {
		uni.navigateTo({
			url: `/pages/privacy/index`
		})
	}
</script>


<style lang="less" scoped>
	.placeholderInputClass {

		font-size: 34rpx;
		// font-family: PingFang SC;
		font-weight: 600;
		color: rgba(255, 255, 255, 0.3);

	}

	.page-login {
		position: relative;
		width: 100%;
		min-height: 100vh;
		background: #182836;
		font-family: PingFang SC;

		.container-logo {
			position: relative;
			width: 100%;
			padding-top: 126rpx;
			box-sizing: border-box;
		}

		.img-title-login {
			position: relative;
			display: block;
			width: 156rpx;
			height: 38rpx;
			margin: 32rpx auto 0;
		}

		.box-login {
			position: relative;
			width: 642rpx;
			height: 257rpx;
			background: #2D4052;
			border-radius: 48rpx;
			box-sizing: border-box;
			margin: 109rpx auto 0;

			display: flex;
			display: -webkit-flex;
			flex-direction: column;

			.box-login-item {
				position: relative;
				width: 100%;
				padding-left: 40rpx;
				padding-right: 40rpx;
				flex: 1;
				flex-shrink: 0;
				border-bottom: 1px solid rgba(255, 255, 255, 0.2);
				box-sizing: border-box;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;

				&:last-child {
					border-bottom: none;
				}

				.txt-input {
					position: relative;
					flex: 1;
					font-size: 34rpx;
					// font-family: PingFang SC;
					font-weight: 600;
					color: #FFFFFF;
					line-height: 34rpx;
					box-sizing: border-box;
					margin-right: 15rpx;
				}

				.icon-login-delete {
					position: relative;
					width: 30rpx;
					height: 30rpx;
				}
			}
		}

		.btn-login {
			position: relative;
			width: 642rpx;
			height: 96rpx;
			line-height: 96rpx;
			// background: linear-gradient(0deg, #10A383 0%, #48C282 100%);
			
			background: linear-gradient(180deg, #00FFF6 0%, #28C0FF 100%);
			

			border-radius: 48rpx;
			box-sizing: border-box;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 600;
			color:#182836;
			opacity: 1;
			margin: 40rpx auto 0;
			text-align: center;

			&.disabled {
				opacity: 0.5;
				color: #FFFFFF;
				
			}
		}

		.wrap-bottom {
			position: fixed;
			width: 100%;
			bottom: 0;
			left: 0;

			.box-privacy {
				position: relative;
				width: 100%;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				padding-bottom: 36rpx;
				box-sizing: border-box;
				line-height: 22px;
				font-size: 22rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #FFFFFF;

				.cont-privacy {
					// color: rgba(72, 194, 130, 1);
					color:#00FFF6;
				}

				.box-agree {
					position: relative;
					width: 30rpx;
					height: 30rpx;
					border-radius: 50%;
					// border: 2rpx solid #FFFFFF;
					box-sizing: border-box;
					background: transparent;
					margin-right: 10rpx;
					.icon-agree{
						position: relative;
						width:100%;
						height: 100%;
					}
				}
			}

		}

		.box-login-type-choose {
			position: relative;
			width: 100%;
			// bottom: 112rpx;
			// bottom: 0;
			// left: 0;
			margin-bottom: 50rpx;

			.box-login-type-title {
				position: relative;
				width: 100%;
				display: flex;
				display: -webkit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.line {
					position: relative;
					width: 198rpx;
					height: 1px;
					background: #E8E9EA;
					opacity: 0.2;
					flex-shrink: 0;
					box-sizing: border-box;
				}

				.cont-title {
					position: relative;
					line-height: 26rpx;
					font-size: 26rpx;
					// font-family: PingFang SC;
					font-weight: 400;
					color: #48C282;
					padding-left: 33rpx;
					padding-right: 33rpx;
				}
			}

			.box-login-type-items {
				position: relative;
				width: 100%;
				display: flex;
				display: -wekbit-flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				margin-top: 50rpx;

				.img-login-type {
					position: relative;
					width: 90rpx;
					height: 90rpx;
					margin-right: 122rpx;

					&:last-child {
						margin-right: 0;
					}
				}
			}



		}

	}
</style>